<template>
	<div v-if="uploading" class="uploading">
		<el-button :size="size" type="primary">上传中{{ jd }}</el-button>
	</div>
	<el-upload
		v-else
		:action="action"
		:show-file-list="false"
		:before-upload="beforeUpload"
		:http-request="httpRequest"
		accept="image/*"
		class="upload-image"
		:name="name"
	>
		<el-button :size="size" type="primary">{{ text }}</el-button>
	</el-upload>
</template>

<script>
import { $POST } from '@/puigins/request.js';
export default {
	props: {
		size: {
			type: String,
			default: 'default'
		},
		action: {
			type: String,
			default: '#'
		},
		text: {
			type: String,
			default: '点击上传'
		},name: {
			type: String,
			default: 'file'
		}
	},
	data() {
		return {
			uploading: false,
			jd: 0
		};
	},
	methods: {
		beforeUpload(file) {
			if (!file.type.startsWith('image/')) {
				this.$message.warning('只能上传图片');
				return false;
			}
			this.uploading = true;
			return true;
		},
		onProgress(e) {
			this.jd = ((e.loaded * 100) / e.total).toFixed(2);
		},
		onSuccess(res) {
			this.uploading = false;
			if (res.data.code === 200) {
				this.$emit('success', res.data);
			} else {
				this.$msgError(res);
			}
		},
		onError(e) {
			this.uploading = false;
			this.$message.error('上传失败');
			console.error(e);
		},
		httpRequest(config) {
			let obj = {};
			Object.assign(obj, config.data);
			obj[this.name]=config.file
			$POST(config.action, obj, {
				responseType: 'json',
				onUploadProgress:this.onProgress
			})
				.then(this.onSuccess)
				.catch(this.onError);
		}
	}
};
</script>

<style lang="scss">
</style>
